<?php


namespace support\bootstrap;


use app\service\statistics\Clients\StatisticClient;
use Webman\Bootstrap;
use Workerman\Timer;
use think\facade\Db;

class ThinkOrm implements Bootstrap
{
    // 进程启动时调用
    public static function start($worker)
    {
        // 配置
        Db::setConfig(config('thinkorm'));
        // 维持mysql心跳
        Timer::add(55, function () {
            $connections = config('thinkorm.connections', []);
            foreach ($connections as $key => $item) {
                if ($item['type'] == 'mysql') {
                    Db::connect($key)->query('select 1');
                }
            }
        });

        Db::listen(function ($sql, $runtime, $master) {
            switch (true) {
                case is_numeric($runtime):
                    $transfer = $sql;
                    $cost     = $runtime;
                    break;
                case !is_numeric($runtime) && 'CONNECT' === substr($sql, 0, 7):
                    @preg_match("/UseTime:([0-9]+(\\.[0-9]+)?|[0-9]+(\\.[0-9]+))/", $sql, $result);
                    if (count($result) > 1) {
                        $transfer = substr($sql, strpos($sql, "s ] ") + 4);
                        $cost     = $result[1];
                    } else {
                        $transfer = $sql;;
                        $cost     = 0;
                    }
                    break;
                default:
                    $transfer = $sql;;
                    $cost     = 0;
                    break;
            }
            StatisticClient::report('', 'projectSql', '127.0.0.1', $transfer, true, 1, json_encode([
                'sql'     => $sql,
                'runtime' => $cost . 's',
                'master'  => $master,
            ], 320), $cost);
        });
    }
}
